# coding='UTF-8'
import pandas as pd
from math import *

PATH = 'data/ml-latest-small/'
ratings = pd.read_csv(PATH + 'ratings.csv')
print(ratings.head(20))
movies = pd.read_csv(PATH + 'movies.csv')
print(movies.head(5))
# 合并数据集，并写入文件中
data = pd.merge(movies, ratings, on='movieId')
print(data.head(5))
data[['userId', 'rating', 'movieId', 'title']].sort_values('userId').to_csv(PATH + 'data.csv', index=False)
files = pd.read_csv(PATH + 'data.csv')
print(files.head(5))

# 将数据data.csv写入字典中
content = []
with open(PATH + 'data.csv') as fp:
    content = fp.readlines()

data = {}
for line in content:
    line = line.strip().split(',')
    # 如果字典中没有某位用户，则使用userId来创建这位用户
    if not line[0] in data.keys():
        data[line[0]] = {line[3]: line[1]}
    # 否则直接添加以该用户ID为key字典中
    else:
        data[line[0]][line[3]] = line[1]


def Euclidean(user1, user2):
    # 取出两位用户评论过的电影和评分
    user1_data = data[user1]
    user2_data = data[user2]
    distance = 0
    # 找到两位用户都评论过的电影，并计算距离
    for key in user1_data.keys():
        if key in user2_data.keys():
            # 注意距离越大，两者越相似
            distance += pow(float(user1_data[key]) - float(user2_data[key]), 2)

    return 1 / (1 + sqrt(distance))

def top10_simliar(userID):
    res = []
    for userid in data.keys():
        if not userid == userID:
            simliar = Euclidean(userID, userid)
            res.append((userid, simliar))
    res.sort(key=lambda val:val[1])
    return res[:4]

# RES = top10_simliar('1')
# print(RES)

def recommend(user):
    # 相似度最高的用户
    top_sim_user = top10_simliar(user)[0][0]
    # 相似度最高的用户的观影记录
    items = data[top_sim_user]
    recommendations = []
    # 筛选出该用户未观看的电影并添加到列表中
    for item in items.keys():
        if item not in data[user].keys():
            recommendations.append((item, items[item]))
    recommendations.sort(key=lambda val:val[1], reverse=True)
    return recommendatios[:10]

Recommendations = recommend('1')
print(Recommendations)